import Cookies from 'js-cookie'
import { fetchPolicy } from '@/api/upload'

const sign_c = 'sign'

const state = {
  sign: JSON.parse(Cookies.get(sign_c) || '""')
}

const mutations = {
  SET_SIGN: (state, sign) => {
    state.sign = sign
    Cookies.set(sign_c, JSON.stringify(sign))
  }
}

const actions = {
  getSign({ commit }, dir) {
    return new Promise((resolve, reject) => {
      // 取签名，判断签名有没有过期
      if (state.sign) {
        const timestamp = Date.parse(new Date())
        if (state.sign.expire - 3000 > timestamp) {
          resolve(state.sign)
        }
      }
      console.log('---------sign.js getSign 27---------')
      fetchPolicy(dir).then(response => {
        const { data } = response
        if (!data) {
          reject('获取验证信息失败.')
        }
        commit('SET_SIGN', data)
        resolve(data)
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
